<?php

/**
 * 供应商订单行为日志处理
 */

namespace App\Service\OrderService;

use App\Amqp\Producer\OrderMessageProducer;
use App\Model\PssLogModel\MicroServiceLog;
use App\Model\PssLogModel\MicroServiceQueryLog;
use App\Model\PssModel\EmalUser;
use App\Service\AppService\SystemCacheConfigService;
use App\Service\BaseService;
use App\Service\HttpServer\HttpCurl;
use Hyperf\Amqp\Producer;
use App\Service\Code\Normal;
use App\Service\TaskServer\TaskWorker;
use Service\AppService\IdService;

class OrderMessageService extends BaseService
{
    //类型（1-订单售后通知,2-订单欠费通知)
    const EVENT_TYPE_ORDER_AFTERSALE   = 1;
    const EVENT_TYPE_ORDER_ACCOUNT_ARREARS = 2;

    //消息发送类型
    protected $message_action = [
        self::EVENT_TYPE_ORDER_AFTERSALE        => 'SendOrderAfterSaleMessage',
        self::EVENT_TYPE_ORDER_ACCOUNT_ARREARS  => 'SendOrderAccountArrearsMessage',
    ];



    /**
     * 添加行为日志表
     * @param string $order_supplier_id
     * @param int $order_mode
     * @param string $contents
     * @param int $receiver_type
     */
    public function publish(int $message_mode, string $mobile = '', array $contents = [], int $receiver_type = 2)
    {
        $MessageBody = [
            'message_mode'          =>  $message_mode,
            'mobile'                =>  $mobile,
            'contents'              =>  $contents,
            'receiver_type'         =>  $receiver_type,
        ];
        try {
            $handlerMessage = new OrderMessageProducer($MessageBody);
            $producer = container()->get(Producer::class);
            $result = $producer->produce($handlerMessage, true);
            if ($result) {
                return Normal::returnCode(Normal::SUC, "发布成功");
            }
            return Normal::returnCode(Normal::FAIL, "操作失败，请稍微再试[100000]");
        } catch (\Throwable $e) {
            return Normal::returnCode(Normal::FAIL, "操作失败，请稍微再试[{$e->getMessage()},{$e->getLine()},{$e->getFile()}]");
        }
    }

    public function syncMessage($data)
    {
        if (empty($data['message_mode'])) {
            return Normal::returnCode(Normal::FAIL, "message_mode不能为空");
        }

        if (!isset($this->message_action[$data['message_mode']])) {
            return Normal::returnCode(Normal::FAIL, "没有找到对应的message_action");
        }

        $actionMethod = $this->message_action[$data['message_mode']];
        return $this->{$actionMethod}($data);
    }

    /**
     * 发送售后订单的消息
     * @param [type] $data
     * @return array
     */
    private function SendOrderAfterSaleMessage($data)
    {
        //获取需要发消息的模板
        $order_sn = $data['contents']['order_sn'];
        $sysconfig = SystemCacheConfigService::instance()->getCacheInfoBySystemCode('sysconfig');
        $ApiCloudH5Url = $sysconfig['WebCloudH5Url'] ?? '';
        if ($ApiCloudH5Url) {
            $string = '或' . $ApiCloudH5Url;
        }
        $temp = " 您有新的订单(编号{$order_sn}) 需要售后审核，请登陆云仓后台 {$string} 查看";
        //获取需要发送短信的对象
        $users = $this->getEmalUsers(2); //获取展示在云仓的用户

        foreach ($users as $user) {
            if (!empty($user['mobile']) && $this->validatePhoneNumber($user['mobile'])) {
                //发送短信
                $this->sendMsg($user['mobile'], $temp, 'SendOrderAfterSaleMessage');
            }
        }
        return Normal::returnCode(Normal::SUC, "发送成功");
    }

    /**
     * 发送售后订单的消息
     * @param [type] $data
     * @return array
     */
    private function SendOrderAccountArrearsMessage($data)
    {
        //获取需要发消息的模板
        $binfo = $data['contents'];
        //判断是否今天已经发送过短信
        $redis = redis();
        $redis->select(SystemCacheConfigService::SYSTEM_CACHE_CONFIG_RDB);
        $key = 'SendOrderAccountArrearsMessage_' . $binfo['bid'];
        //获取是否发送过短信
        $isExistSendMsg = $redis->get($key);
        if ($isExistSendMsg) {
            return Normal::returnCode(Normal::SUC, "今天已经发过短信");
        }
        if (!$this->validatePhoneNumber($data['mobile'])) {
            return Normal::returnCode(Normal::SUC, "手机格式不正确");
        }

        $temp = " 尊敬的客户您好！你在云仓的发货预付款余额不足，请联系我司的运营进行充值。充值后对余额不足卡住的订单进行重推，谢谢。";
        $this->sendMsg($data['mobile'], $temp, 'SendOrderAccountArrearsMessage');
        //记录redis 
        $expire = strtotime(date('Y-m-d 23:59:59')) - time();
        $redis->set($key,$key,$expire);
        return Normal::returnCode(Normal::SUC, "发送成功");
    }

    public function sendMsg($mobile, $message, $method)
    {

        //测试环境不发送短信
        $is_production = config('api.APP_ENV');
        if ($is_production) {

            $config   = SystemCacheConfigService::instance()->getCacheInfoBySystemCode('sms');
            if (empty($config)) {
                return Normal::returnCode(Normal::FAIL, "发送短信失败，短信未配置，请联系相应业务人员处理！");
            }
            //检查对应字段
            $fields = ['keyword', 'sname', 'spwd', 'sprdid', 'api_url'];
            $res    = SystemCacheConfigService::instance()->checkAllowApiColumnsByFields($config, $fields);
            if ($res['code'] != Normal::SUC) {
                return $res;
            }

            $keyword    = $config['keyword'];

            $data = [
                'sname'   => $config['sname'],
                'spwd'    => $config['spwd'],
                'scorpid' => '',
                'sprdid'  => $config['sprdid'],
                'sdst'    => $mobile,
                'smsg'    => "【{$keyword}】" . $message,
            ];
            $val = [
                'tag'       => 'SmsMessage_' . $method,
                'url'       => $config['api_url'],
                'data'      => $data,
                'method'    => 'post',
                'format'    => 'form-data',
                'header'    => []
            ];

            $start_time = microtime(true);

            $res = HttpCurl::instance()->apiRequest($val['url'],$val['data'],$val['method'],$val['format'],$val['header']);

            $used_time = bcsub(microtime(true), $start_time,3);

            $response_data = json_decode($res['result'],true);
            $response_data = !empty($response_data) ? json_encode($response_data,JSON_UNESCAPED_UNICODE) : $res['result'];

            MicroServiceLog::instance()->addLog([
                'interface_code'    => $val['tag'],
                'request_url'       => $val['url'],
                'request_param'     => json_encode($val['data'],JSON_UNESCAPED_UNICODE),
                'response_code'     => $res['httpCode'],
                'response_data'     => $response_data,
                'req_used_time'     => $used_time,
            ]);

            $res = json_decode(json_encode(simplexml_load_string($res['result'], 'SimpleXMLElement', LIBXML_NOCDATA)), true);

            if (!isset($res['State']) || $res['State'] != 0) {
                return Normal::returnCode(Normal::FAIL, "短信发送失败");
            }
        }
        return Normal::returnCode(Normal::SUC, "发送成功");
    }

    public function getEmalUsers($status = '')
    {
        $where = [];
        if (!empty($status)) {
            $where['status'] = $status;
        }
        $users = EmalUser::instance()->where($where)->get()->toArray();
        return $users;
    }

    private function validatePhoneNumber($phoneNumber)
    {
        // 移动电话号码格式：1开头的11位数字，例如13812345678  
        $pattern = '/^1[3456789]\d{9}$/';
        // 使用preg_match函数进行正则匹配  
        if (preg_match($pattern, $phoneNumber)) {
            return true; // 验证通过  
        } else {
            return false; // 验证失败  
        }
    }
}
